ConvertPixelType.py

Convert Image Format

It shows how to convert the raw image data acquired by the camera to the desired pixel format via the image format conversion API.

1 # -- coding: utf-8 --
2 
3 import sys
4 import copy
5 import platform
6 import os
7 
8 from ctypes import *
9 
10 # Compatible with different operating systems to load DDL
11 currentsystem = platform.system()
12 if currentsystem == 'Windows':
13  sys.path.append(os.path.join(os.getenv('MVCAM_COMMON_RUNENV'), "Samples", "Python", "MvImport"))
14 else:
15  sys.path.append(os.path.join("..", "..", "MvImport"))
16 from MvCameraControl_class import *
17 
18 # Compatible with input processing of Python 2.X and 3.X
19 if sys.version_info[0] < 3:
20  # Python 2.x
21  input_func = raw_input
22 else:
23  # Python 3.x
24  input_func = input
25 
26 # Decoding Characters
27 def decoding_char(ctypes_char_array):
28  """
29  Safely decode a string from a ctypes character array.
30  Compatible with Python 2.x and 3.x, as well as 32-bit and 64-bit environments.
31  """
32  byte_str = memoryview(ctypes_char_array).tobytes()
33 
34  # Truncate at the first null character
35  null_index = byte_str.find(b'\x00')
36  if null_index != -1:
37  byte_str = byte_str[:null_index]
38 
39  # Attempt to decode using multiple encodings
40  for encoding in ['gbk', 'utf-8', 'latin-1']:
41  try:
42  return byte_str.decode(encoding)
43  except UnicodeDecodeError:
44  continue
45 
46  # If all encodings fail, use a replacement strategy
47  return byte_str.decode('latin-1', errors='replace')
48 
49 
50 if __name__ == "__main__":
51 
52  try:
53  # Initialize SDK resources
54  MvCamera.MV_CC_Initialize()
55 
56  SDKVersion = MvCamera.MV_CC_GetSDKVersion()
57  print ("SDKVersion[0x%x]" % SDKVersion)
58 
59  deviceList = MV_CC_DEVICE_INFO_LIST()
60  tlayerType = (MV_GIGE_DEVICE | MV_USB_DEVICE | MV_GENTL_CAMERALINK_DEVICE
61  | MV_GENTL_CXP_DEVICE | MV_GENTL_XOF_DEVICE)
62 
63  # Enumerate devices
64  ret = MvCamera.MV_CC_EnumDevices(tlayerType, deviceList)
65  if ret != 0:
66  print ("enum devices fail! ret[0x%x]" % ret)
67  sys.exit()
68 
69  if deviceList.nDeviceNum == 0:
70  print ("find no device!")
71  sys.exit()
72 
73  print ("find %d devices!" % deviceList.nDeviceNum)
74 
75  for i in range(0, deviceList.nDeviceNum):
76  mvcc_dev_info = cast(deviceList.pDeviceInfo[i], POINTER(MV_CC_DEVICE_INFO)).contents
77  if mvcc_dev_info.nTLayerType == MV_GIGE_DEVICE or mvcc_dev_info.nTLayerType == MV_GENTL_GIGE_DEVICE:
78  print ("\ngige device: [%d]" % i)
79  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stGigEInfo.chModelName)
80  print ("device model name: %s" % strModeName)
81  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stGigEInfo.chSerialNumber)
82  print("device serial number: %s" % strSerialNumber)
83 
84  nip1 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0xff000000) >> 24)
85  nip2 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x00ff0000) >> 16)
86  nip3 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x0000ff00) >> 8)
87  nip4 = (mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x000000ff)
88  print ("current ip: %d.%d.%d.%d\n" % (nip1, nip2, nip3, nip4))
89  elif mvcc_dev_info.nTLayerType == MV_USB_DEVICE:
90  print ("\nu3v device: [%d]" % i)
91  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stUsb3VInfo.chModelName)
92  print ("device model name: %s" % strModeName)
93 
94  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stUsb3VInfo.chSerialNumber)
95  print ("device serial number: %s" % strSerialNumber)
96  elif mvcc_dev_info.nTLayerType == MV_GENTL_CAMERALINK_DEVICE:
97  print ("\nCML device: [%d]" % i)
98  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stCMLInfo.chModelName)
99  print ("device model name: %s" % strModeName)
100 
101  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stCMLInfo.chSerialNumber)
102  print ("device serial number: %s" % strSerialNumber)
103  elif mvcc_dev_info.nTLayerType == MV_GENTL_CXP_DEVICE:
104  print ("\nCXP device: [%d]" % i)
105  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stCXPInfo.chModelName)
106  print ("device model name: %s" % strModeName)
107 
108  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stCXPInfo.chSerialNumber)
109  print ("device serial number: %s" % strSerialNumber)
110  elif mvcc_dev_info.nTLayerType == MV_GENTL_XOF_DEVICE:
111  print ("\nXoF device: [%d]" % i)
112  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stXoFInfo.chModelName)
113  print ("device model name: %s" % strModeName)
114 
115  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stXoFInfo.chSerialNumber)
116  print ("device serial number: %s" % strSerialNumber)
117 
118  nConnectionNum = input_func("please input the number of the device to connect:")
119 
120  if int(nConnectionNum) >= deviceList.nDeviceNum:
121  print ("intput error!")
122  sys.exit()
123 
124  # Create the camera instance
125  cam = MvCamera()
126 
127  # Select a device, and create a handle
128  stDeviceList = cast(deviceList.pDeviceInfo[int(nConnectionNum)], POINTER(MV_CC_DEVICE_INFO)).contents
129 
130  ret = cam.MV_CC_CreateHandle(stDeviceList)
131  if ret != 0:
132  raise Exception ("create handle fail! ret[0x%x]" % ret)
133 
134  # Turn on the device
135  ret = cam.MV_CC_OpenDevice(MV_ACCESS_Exclusive, 0)
136  if ret != 0:
137  raise Exception ("open device fail! ret[0x%x]" % ret)
138 
139  # Get optimal packet size (only supported by GigE devices)
140  if stDeviceList.nTLayerType == MV_GIGE_DEVICE or stDeviceList.nTLayerType == MV_GENTL_GIGE_DEVICE:
141  nPacketSize = cam.MV_CC_GetOptimalPacketSize()
142  if int(nPacketSize) > 0:
143  ret = cam.MV_CC_SetIntValue("GevSCPSPacketSize",nPacketSize)
144  if ret != 0:
145  print ("Warning: Set Packet Size fail! ret[0x%x]" % ret)
146  else:
147  print ("Warning: Get Packet Size fail! ret[0x%x]" % nPacketSize)
148 
149  # Set trigger mode to off
150  ret = cam.MV_CC_SetEnumValue("TriggerMode", MV_TRIGGER_MODE_OFF)
151  if ret != 0:
152  raise Exception ("set trigger mode fail! ret[0x%x]" % ret)
153 
154  # Start grabbing images
155  ret = cam.MV_CC_StartGrabbing()
156  if ret != 0:
157  raise Exception ("start grabbing fail! ret[0x%x]" % ret)
158 
159  stOutFrame = MV_FRAME_OUT()
160  memset(byref(stOutFrame), 0, sizeof(stOutFrame))
161 
162  # Set interpolation method to equilibrium
163  ret = cam.MV_CC_SetBayerCvtQuality(1)
164  if ret != 0:
165  raise Exception ("set Bayer convert quality fail! ret[0x%x]" % ret)
166 
167  ret = cam.MV_CC_GetImageBuffer(stOutFrame, 1000)
168  if None != stOutFrame.pBufAddr and 0 == ret :
169  print ("get one frame: Width[%d], Height[%d], nFrameNum[%d]" % (stOutFrame.stFrameInfo.nWidth, stOutFrame.stFrameInfo.nHeight, stOutFrame.stFrameInfo.nFrameNum))
170 
171  nRGBSize = stOutFrame.stFrameInfo.nWidth * stOutFrame.stFrameInfo.nHeight * 3
172  stConvertParam = MV_CC_PIXEL_CONVERT_PARAM_EX()
173  memset(byref(stConvertParam), 0, sizeof(stConvertParam))
174  stConvertParam.nWidth = stOutFrame.stFrameInfo.nWidth
175  stConvertParam.nHeight = stOutFrame.stFrameInfo.nHeight
176  stConvertParam.pSrcData = stOutFrame.pBufAddr
177  stConvertParam.nSrcDataLen = stOutFrame.stFrameInfo.nFrameLen
178  stConvertParam.enSrcPixelType = stOutFrame.stFrameInfo.enPixelType
179  stConvertParam.enDstPixelType = PixelType_Gvsp_RGB8_Packed
180  stConvertParam.pDstBuffer = (c_ubyte * nRGBSize)()
181  stConvertParam.nDstBufferSize = nRGBSize
182 
183  ret = cam.MV_CC_ConvertPixelTypeEx(stConvertParam)
184  if ret != 0:
185  raise Exception ("convert pixel fail! ret[0x%x]" % ret)
186 
187  cam.MV_CC_FreeImageBuffer(stOutFrame)
188 
189  print ("convert pixeltype succeed!")
190 
191  file_path = "AfterConvert_RGB.raw"
192  file_open = open(file_path.encode('ascii'), 'wb+')
193  try:
194  img_buff = (c_ubyte * stConvertParam.nDstLen)()
195  memmove(byref(img_buff), stConvertParam.pDstBuffer, stConvertParam.nDstLen)
196  file_open.write(img_buff)
197  except:
198  raise Exception("save file executed failed:%s" % e.message)
199  finally:
200  file_open.close()
201  else:
202  print ("get one frame fail, ret[0x%x]" % ret)
203 
204  print ("press Enter key to stop grabbing.")
205  input_func()
206 
207  # Stop grabbing images
208  ret = cam.MV_CC_StopGrabbing()
209  if ret != 0:
210  raise Exception ("stop grabbing fail! ret[0x%x]" % ret)
211 
212  # Turn off the device
213  ret = cam.MV_CC_CloseDevice()
214  if ret != 0:
215  raise Exception ("close deivce fail! ret[0x%x]" % ret)
216 
217  # Destroy the handle
218  cam.MV_CC_DestroyHandle()
219 
220 
221  except Exception as e:
222  print(e)
223  cam.MV_CC_CloseDevice()
224  cam.MV_CC_DestroyHandle()
225  finally:
226  # Release SDK resources
227  MvCamera.MV_CC_Finalize()